package com.example.api.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.api.entity.LoginReq;
import com.example.api.entity.Userlist;
import com.example.api.service.UserlistService;
import com.example.api.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @Autowired
    UserlistService userlistService;

    /**
     * 登陆系统
     * @param form
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginReq form) {
//        Integer userId = userService.login(form);
        Userlist user = new Userlist();
        user.setAccount(form.getUsername());
        user.setPassword(form.getPassword());
        Userlist userlist = userlistService.getOne(new QueryWrapper<>(user));
        if (userlist == null) {
            return R.error();
        }
        Integer userId = userlist.getId();
        R r = R.ok().put("result", userId != null ? true : false);
        if (userId != null) {
            StpUtil.login(userId);
            String token = StpUtil.getTokenInfo().getTokenValue();
            r.put("token", token).put("userId",userId);
        }
        return r;
    }


    /**
     * 退出系统
     * @return
     */
    @GetMapping("/logout")
    public R logout() {
        StpUtil.logout();
        return R.ok();
    }

}
